package cn.zxy.config;

import cn.zxy.exception.BizException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

//@ControllerAdvice
//第三种处理异常的方式
//@ControllerAdvice + @ExceptionHandler
public class MyExceptionAdvice {
    @ExceptionHandler(BizException.class)
    public ModelAndView error(BizException ex){
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg",ex.getCode()+"==>"+ex.toString());
        mv.setViewName("biz");
        return mv;
    }

    //全局处理
    //这三种形式是一样的，第一种是最标准的，value可以省去
//    @ExceptionHandler(value = Exception.class)
//    @ExceptionHandler

//    @ExceptionHandler(Exception.class)
//    public ModelAndView error(Exception ex){
//        ModelAndView mv = new ModelAndView("error");
//        mv.addObject("msg",ex.getMessage());
//        return mv;
//    }

//    @ExceptionHandler(NullPointerException.class)
//    public ModelAndView error2(NullPointerException ex){
//        ModelAndView mv = new ModelAndView("nullPoint");
//        mv.addObject("msg",ex.getMessage());
//        return mv;
//    }
//
//    @ExceptionHandler(ArithmeticException.class)
//    public ModelAndView error3(ArithmeticException ex){
//        ModelAndView mv = new ModelAndView("arith");
//        mv.addObject("msg",ex.getMessage());
//        return mv;
//    }

    //简化代码
//    @ExceptionHandler(Exception.class)
//    public ModelAndView error4(Exception ex){
//        ModelAndView mv = new ModelAndView();
//        if (ex instanceof ArithmeticException){
//            mv.setViewName("arith");
//            mv.addObject("msg",ex.getMessage());
//        } else if (ex instanceof NullPointerException) {
//            mv.setViewName("nullPoint");
//            mv.addObject("msg",ex.toString());
//        }else{
//            mv.setViewName("error");
//            mv.addObject("msg",ex.getMessage());
//        }
//        return mv;
//    }

}
